<template>
  <view class="home-container" :style="{backgroundColor: bgColor}">
    <!-- 顶部状态栏 -->
    <view class="status-bar"></view>
    
    <!-- 主内容区 -->
    <scroll-view 
      scroll-y 
      class="scroll-content"
      :style="{height: scrollHeight}"
    >
      <!-- 搜索栏 -->
      <view class="search-bar">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input 
          class="search-input" 
          v-model="searchKeyword"
          placeholder="搜索景点/城市/关键词" 
          placeholder-class="placeholder-style"
          @confirm="handleSearch"
          @input="handleInputChange"
        />
        <uni-icons 
          v-if="searchKeyword" 
          type="clear" 
          size="16" 
          color="#999"
          @click="clearSearch"
        ></uni-icons>
      </view>
      
      <!-- 搜索历史 -->
      <view v-if="searchHistory.length > 0 && !searchKeyword && !searchResults.length" class="search-history">
        <view class="history-header">
          <text class="history-title">搜索历史</text>
          <text class="clear-history" @click="clearHistory">清空</text>
        </view>
        <view class="history-tags">
          <text 
            v-for="(item, index) in searchHistory" 
            :key="index"
            class="history-tag"
            @click="searchByHistory(item)"
          >{{ item }}</text>
        </view>
      </view>
      
      <!-- 搜索建议 -->
      <view v-if="searchSuggestions.length > 0 && searchKeyword && !searchResults.length" class="search-suggestions">
        <view 
          v-for="(suggestion, index) in searchSuggestions" 
          :key="index"
          class="suggestion-item"
          @click="searchBySuggestion(suggestion)"
        >
          <uni-icons type="search" size="14" color="#999"></uni-icons>
          <text class="suggestion-text">{{ suggestion }}</text>
        </view>
      </view>
      
      <!-- 搜索结果 -->
      <view v-if="searchResults.length > 0" class="search-results">
        <view class="results-header">
          <text class="results-title">搜索结果 ({{ total }})</text>
          <text class="clear-results" @click="clearSearch">清空</text>
        </view>
        
        <view class="results-list">
          <view 
            v-for="(item, index) in searchResults" 
            :key="item.id"
            class="result-item"
            @click="navToDestination(item)"
          >
            <view class="result-content">
              <text class="result-name">{{ item.name }}</text>
              <text class="result-desc">{{ item.description }}</text>
              <view class="result-tags">
                <text class="tag preference">{{ item.preferenceType }}</text>
                <text class="tag budget">¥{{ item.minBudget }}-{{ item.maxBudget }}</text>
                <text class="tag season">{{ item.bestSeason }}</text>
              </view>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 分页控件 -->
        <view v-if="totalPages > 1" class="pagination">
          <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
          <text class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</text>
          <button @click="nextPage" :disabled="currentPage >= totalPages">下一页</button>
        </view>
      </view>
      
      <!-- 默认内容（当没有搜索时显示） -->
      <view v-if="!searchKeyword && !searchResults.length">
        <!-- 天气快捷入口 -->
        <view class="weather-card" @click="navToWeather">
          <text class="location">当前位置</text>
          <view class="weather-info">
            <text class="temp">28°C</text>
            <text class="condition">晴</text>
          </view>
          <uni-icons type="right" size="16" color="#666"></uni-icons>
        </view>
        
        <!-- 推荐标题 -->
        <view class="section-title">
          <text class="title-text">猜你喜欢</text>
          <text class="more">更多</text>
        </view>
        
        <!-- 横向滚动推荐 -->
        <scroll-view 
          scroll-x 
          class="recommend-scroll"
          show-scrollbar="false"
        >
          <view 
            v-for="item in recommendList" 
            :key="item.id" 
            class="recommend-item"
            @click="navToAttraction(item)"
          >
            <image :src="item.image" mode="aspectFill" class="recommend-image"></image>
            <text class="item-title">{{ item.title }}</text>
            <text class="item-desc">{{ item.desc }}</text>
          </view>
        </scroll-view>
        
        <!-- 热门目的地 -->
        <view class="section-title">
          <text class="title-text">热门目的地</text>
        </view>
        
        <view class="grid-container">
          <view 
            v-for="city in hotCities" 
            :key="city.name"
            class="grid-item"
            @click="navToCity(city)"
          >
            <image :src="city.image" class="city-image"></image>
            <text class="city-name">{{ city.name }}</text>
            <text class="heat-index">热度: {{ city.heat }}%</text>
          </view>
        </view>
        
        <!-- 限时优惠 -->
        <view class="discount-banner">
          <swiper 
            autoplay 
            circular
            interval="3000"
          >
            <swiper-item v-for="(item, index) in discounts" :key="index">
              <view class="banner-content">
                <text class="discount-text">{{ item.text }}</text>
                <text class="discount-time">剩余: {{ item.time }}</text>
              </view>
            </swiper-item>
          </swiper>
        </view>
      </view>
    </scroll-view>
    
    <!-- 底部导航 -->
    <view class="tab-bar">
      <view 
        v-for="(tab, index) in tabs" 
        :key="tab.text"
        class="tab-item"
        :class="{active: currentTab === index}"
        @click="switchTab(index)"
      >
        <uni-icons :type="tab.icon" size="24" :color="currentTab === index ? activeColor : inactiveColor"></uni-icons>
        <text>{{ tab.text }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 设计色调配置（与登录页保持一致）
const bgColor = '#f8f8f8'
const activeColor = '#1a8cff' // 主色调
const inactiveColor = '#666'

// 响应式数据
const scrollHeight = ref('')
const currentTab = ref(0) // 首页默认选中

// 搜索相关数据
const searchKeyword = ref('')
const searchHistory = ref([])
const searchSuggestions = ref([])
const searchResults = ref([])
const currentPage = ref(1)
const total = ref(0)
const totalPages = ref(0)
const loading = ref(false)

// 搜索建议关键词
const suggestionKeywords = [
  '主题乐园', '海滨度假', '历史古迹', '自然风光', '美食', '购物',
  '亲子游玩', '情侣出游', '商务出行', '温泉', '滑雪', '古镇',
  '春季', '夏季', '秋季', '冬季', '全年'
]

const recommendList = ref([
  { id: 1, image: '/static/home/sanyawan.webp', title: '三亚湾', desc: '碧海蓝天度假胜地' },
  { id: 2, image: '/static/home/gugong.webp', title: '故宫博物院', desc: '穿越千年的历史对话' },
  { id: 3, image: '/static/home/Disney.webp', title: '上海迪士尼', desc: '梦幻童话世界' }
])

const hotCities = ref([
  { name: '三亚', image: '/static/home/sanya.webp', heat: 92 },
  { name: '西安', image: '/static/home/xian.webp', heat: 88 },
  { name: '成都', image: '/static/home/chengdu.webp', heat: 85 }
])

const discounts = ref([
  { text: '限时特惠 | 三亚5日游套餐立减500', time: '23:59:59' },
  { text: '国庆预售 | 西安兵马俑门票7折', time: '3天12小时' }
])

// 在这里直接添加统计项
const tabs = ref([
  { icon: 'home', text: '首页' },
  { icon: 'eye', text: '发现' },
  { icon: 'calendar', text: '行程' },
  { icon: 'person', text: '我的' },
  { icon: 'map', text: '统计' } // 新增统计项
])

// 生命周期
onMounted(() => {
  calcScrollHeight()
  loadSearchHistory()
})

onLoad(() => {
  uni.setNavigationBarTitle({ title: '景点旅游助手' })
})

// 方法定义
const calcScrollHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  scrollHeight.value = `${systemInfo.windowHeight - 50}px` // 减去tabbar高度
}

// 搜索相关方法
const handleInputChange = (e) => {
  const value = e.detail.value
  searchKeyword.value = value
  
  if (value) {
    // 生成搜索建议
    searchSuggestions.value = suggestionKeywords.filter(keyword => 
      keyword.includes(value)
    ).slice(0, 5)
  } else {
    searchSuggestions.value = []
    searchResults.value = []
  }
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    performSearch()
  }
}

const performSearch = async () => {
  if (!searchKeyword.value.trim()) return
  
  loading.value = true
  
  try {
    // 构造请求参数
    const requestData = {
      searchContent: searchKeyword.value.trim(),
      page: currentPage.value,
      size: 10
    }

    console.log('发送搜索请求:', requestData)

    // 发送请求
    const result = await new Promise((resolve, reject) => {
      uni.request({
        url: 'http://192.168.165.171:8080/api/recommendations/destinations/search',
        method: 'POST',
        data: requestData,
        header: {
          'Content-Type': 'application/json',
        },
        success: (res) => {
          resolve(res)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })

    console.log('搜索返回数据:', result.data)

    if (result.statusCode === 200) {
      const responseData = result.data
      
      if (responseData && Array.isArray(responseData.content)) {
        searchResults.value = responseData.content
        total.value = responseData.total || 0
        totalPages.value = responseData.totalPages || 0
        currentPage.value = responseData.page || 1
        
        // 保存搜索历史
        saveSearchHistory(searchKeyword.value.trim())
        
        if (responseData.content.length > 0) {
          uni.showToast({
            title: `找到${total.value}个相关景点`,
            icon: 'success',
            duration: 2000
          })
        } else {
          uni.showToast({
            title: '暂无相关景点',
            icon: 'none',
            duration: 2000
          })
        }
      } else {
        throw new Error('返回数据格式不正确')
      }
    } else {
      throw new Error(`搜索失败: ${result.data?.message || `状态码: ${result.statusCode}`}`)
    }
  } catch (error) {
    console.error('搜索失败:', error)
    uni.showToast({
      title: error.message || '搜索失败，请稍后重试',
      icon: 'none',
      duration: 3000
    })
    
    searchResults.value = []
    total.value = 0
    totalPages.value = 0
  } finally {
    loading.value = false
  }
}

const searchByHistory = (keyword) => {
  searchKeyword.value = keyword
  performSearch()
}

const searchBySuggestion = (suggestion) => {
  searchKeyword.value = suggestion
  performSearch()
}

const clearSearch = () => {
  searchKeyword.value = ''
  searchResults.value = []
  searchSuggestions.value = []
  currentPage.value = 1
  total.value = 0
  totalPages.value = 0
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    performSearch()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    performSearch()
  }
}

// 搜索历史相关方法
const loadSearchHistory = () => {
  try {
    const history = uni.getStorageSync('searchHistory')
    if (history) {
      searchHistory.value = JSON.parse(history)
    }
  } catch (error) {
    console.error('加载搜索历史失败:', error)
  }
}

const saveSearchHistory = (keyword) => {
  try {
    let history = searchHistory.value
    
    // 移除重复项
    history = history.filter(item => item !== keyword)
    
    // 添加到开头
    history.unshift(keyword)
    
    // 限制历史记录数量
    if (history.length > 10) {
      history = history.slice(0, 10)
    }
    
    searchHistory.value = history
    uni.setStorageSync('searchHistory', JSON.stringify(history))
  } catch (error) {
    console.error('保存搜索历史失败:', error)
  }
}

const clearHistory = () => {
  searchHistory.value = []
  uni.removeStorageSync('searchHistory')
}

// 导航方法
const switchTab = (index) => {
  currentTab.value = index
  
  // 根据不同的标签跳转到对应页面
  switch(index) {
    case 0:
      // 当前就是首页，不需要跳转
      break
    case 1:
      // 跳转到发现页面
      uni.navigateTo({ 
        url: '/pages/find/find' 
      })
      break
    case 2:
      // 跳转到行程页面
      uni.navigateTo({ 
        url: '/pages/recommend/recommend' 
      })
      break
    case 3:
      // 跳转到我的页面
      uni.navigateTo({ 
        url: '/pages/user/user' 
      })
      break
    case 4: // 新增统计页面跳转逻辑
      uni.navigateTo({
        url: '/pages/statistics/statistics'
      })
      break
  }
}

const navToWeather = () => {
  uni.navigateTo({ url: '/pages/weather/index' })
}

const navToCity = (city) => {
  uni.navigateTo({ 
    url: `/pages/city/index?name=${encodeURIComponent(city.name)}` 
  })
}

const navToAttraction = (item) => {
  // 跳转到景点详情页
  uni.navigateTo({ 
    url: `/pages/details/details?id=${item.id}&name=${encodeURIComponent(item.title)}` 
  })
}

const navToDestination = (destination) => {
  // 跳转到目的地详情页
  uni.navigateTo({ 
    url: `/pages/details/details?id=${destination.id}&name=${encodeURIComponent(destination.name)}` 
  })
}
</script>

<style lang="scss">
.home-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  box-sizing: border-box;
  background-color: #f5f7fa;
  
  .status-bar {
    height: var(--status-bar-height);
    background-color: #f8f8f8;
  }
  
  .scroll-content {
    padding: 15px;
    box-sizing: border-box;
  }
  
  .search-bar {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 20px;
    padding: 8px 15px;
    margin-bottom: 15px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
    
    .search-input {
      flex: 1;
      margin-left: 8px;
      margin-right: 8px;
      font-size: 14px;
      width: 100%;
    }
    
    .placeholder-style {
      color: #999;
    }
  }
  
  .search-history {
    background-color: #fff;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 15px;
    
    .history-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      .history-title {
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
      
      .clear-history {
        font-size: 12px;
        color: #999;
      }
    }
    
    .history-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      
      .history-tag {
        padding: 6px 12px;
        background-color: #f0f0f0;
        border-radius: 15px;
        font-size: 12px;
        color: #666;
      }
    }
  }
  
  .search-suggestions {
    background-color: #fff;
    border-radius: 12px;
    margin-bottom: 15px;
    
    .suggestion-item {
      display: flex;
      align-items: center;
      padding: 12px 15px;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .suggestion-text {
        margin-left: 8px;
        font-size: 14px;
        color: #333;
      }
    }
  }
  
  .search-results {
    .results-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .results-title {
        font-size: 16px;
        color: #333;
        font-weight: 500;
      }
      
      .clear-results {
        font-size: 12px;
        color: #999;
      }
    }
    
    .results-list {
      .result-item {
        display: flex;
        align-items: center;
        background-color: #fff;
        border-radius: 12px;
        padding: 15px;
        margin-bottom: 10px;
        
        .result-content {
          flex: 1;
          
          .result-name {
            display: block;
            font-size: 16px;
            color: #333;
            font-weight: 500;
            margin-bottom: 5px;
          }
          
          .result-desc {
            display: block;
            font-size: 12px;
            color: #666;
            margin-bottom: 8px;
            line-height: 1.4;
          }
          
          .result-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            
            .tag {
              padding: 2px 6px;
              border-radius: 8px;
              font-size: 10px;
              
              &.preference {
                background-color: #e3f2fd;
                color: #1976d2;
              }
              
              &.budget {
                background-color: #f3e5f5;
                color: #7b1fa2;
              }
              
              &.season {
                background-color: #e8f5e8;
                color: #388e3c;
              }
            }
          }
        }
      }
    }
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
    gap: 10px;
    
    button {
      padding: 8px 15px;
      background: #1a8cff;
      color: white;
      border-radius: 6px;
      font-size: 12px;
      border: none;
      
      &[disabled] {
        background: #ccc;
        opacity: 0.6;
      }
      
      &::after {
        border: none;
      }
    }
    
    .page-info {
      font-size: 12px;
      color: #666;
    }
  }
  
  .weather-card {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 12px;
    padding: 12px 15px;
    margin-bottom: 20px;
    
    .location {
      font-size: 14px;
      color: #333;
      margin-right: auto;
    }
    
    .weather-info {
      display: flex;
      align-items: center;
      margin-right: 15px;
      
      .temp {
        font-size: 18px;
        font-weight: bold;
        color: #333;
        margin-right: 8px;
      }
      
      .condition {
        font-size: 12px;
        color: #666;
      }
    }
  }
  
  .section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 15px 0;
    
    .title-text {
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }
    
    .more {
      font-size: 12px;
      color: #999;
    }
  }
  
  .recommend-scroll {
    white-space: nowrap;
    margin-bottom: 20px;
    width: 100%;
    
    .recommend-item {
      display: inline-block;
      width: 120px;
      margin-right: 12px;
      background-color: #fff;
      border-radius: 8px;
      overflow: hidden;
      vertical-align: top;
      
      .recommend-image {
        width: 100%;
        height: 80px;
        display: block;
      }
      
      .item-title {
        display: block;
        font-size: 14px;
        color: #333;
        padding: 5px 8px 0;
        white-space: normal;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }
      
      .item-desc {
        display: block;
        font-size: 10px;
        color: #999;
        padding: 0 8px 8px;
        white-space: normal;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }
    }
  }
  
  .grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    margin-bottom: 20px;
    
    .grid-item {
      background-color: #fff;
      border-radius: 8px;
      overflow: hidden;
      
      .city-image {
        width: 100%;
        height: 80px;
        display: block;
      }
      
      .city-name {
        display: block;
        font-size: 15px;
        font-weight: bold;
        color: #333;
        padding: 5px 8px 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .heat-index {
        display: block;
        font-size: 10px;
        color: #ff6b6b;
        padding: 0 8px 8px;
      }
    }
  }
  
  .discount-banner {
    height: 80px;
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 15px;
    overflow: hidden;
    
    .banner-content {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding-left: 15px;
      
      .discount-text {
        font-size: 14px;
        color: #333;
        margin-bottom: 5px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .discount-time {
        font-size: 12px;
        color: #ff6b6b;
      }
    }
  }
  
  .tab-bar {
    display: flex;
    height: 50px;
    background-color: #fff;
    box-shadow: 0 -2px 6px rgba(0,0,0,0.05);
    
    .tab-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      font-size: 10px;
      color: #666;
      
      &.active {
        color: #1a8cff;
      }
    }
  }
}
</style>